<template>
	<div class="feedback-manage-container">
		<div class="page-header">
			<h2>反馈管理</h2>
			<div class="header-actions">
				<el-button type="primary" @click="fetchFeedbackList" :loading="loading">
					<el-icon><Refresh /></el-icon>刷新
				</el-button>
				<el-button
					type="danger"
					@click="handleBatchDelete"
					:disabled="selectedFeedbacks.length === 0"
				>
					<el-icon><Delete /></el-icon>批量删除
				</el-button>
			</div>
		</div>

		<!-- 搜索筛选区域 -->
		<el-card class="filter-card">
			<el-form :model="filterForm" inline>
				<el-form-item label="反馈类型">
					<el-select v-model="filterForm.type" placeholder="全部类型" clearable>
						<el-option label="功能优化" value="功能优化" />
						<el-option label="新功能建议" value="新功能建议" />
						<el-option label="性能问题" value="性能问题" />
						<el-option label="功能异常" value="功能异常" />
						<el-option label="Bug反馈" value="Bug反馈" />
					</el-select>
				</el-form-item>
				<el-form-item label="处理状态">
					<el-select v-model="filterForm.status" placeholder="全部状态" clearable>
						<el-option label="已解决" value="resolved" />
						<el-option label="解决中" value="resolving" />
						<el-option label="不解决" value="noResolved" />
					</el-select>
				</el-form-item>
				<!-- <el-form-item label="关键词">
					<el-input v-model="filterForm.keyword" placeholder="标题/内容关键词" clearable />
				</el-form-item> -->
				<el-form-item>
					<el-button type="primary" @click="handleFilter">
						<el-icon><Search /></el-icon>搜索
					</el-button>
					<el-button @click="resetFilter">
						<el-icon><RefreshRight /></el-icon>重置
					</el-button>
				</el-form-item>
			</el-form>
		</el-card>

		<!-- 数据表格区域 -->
		<el-card class="data-card">
			<div v-if="loading" class="loading-container">
				<el-skeleton :rows="6" animated />
			</div>

			<div v-else-if="feedbackList.length === 0" class="empty-data">
				<el-empty description="暂无反馈数据" />
			</div>

			<el-table
				v-else
				:data="feedbackList"
				style="width: 100%"
				@selection-change="handleSelectionChange"
				border
			>
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column prop="id" label="ID" width="80" align="center" />
				<el-table-column prop="title" label="标题" min-width="240" show-overflow-tooltip>
					<template #default="scope">
						<el-link type="primary" :underline="false" @click="handleViewDetail(scope.row)">
							{{ scope.row.title }}
						</el-link>
					</template>
				</el-table-column>
				<el-table-column prop="type" label="类型" width="100" align="center" />
				<el-table-column label="用户" width="100" align="center">
					<template #default="scope">
						<span>用户{{ scope.row.userId }}</span>
					</template>
				</el-table-column>
				<el-table-column label="创建时间" width="160" align="center">
					<template #default="scope">
						{{ formatDate(scope.row.createTime) }}
					</template>
				</el-table-column>
				<el-table-column label="状态" width="100" align="center">
					<template #default="scope">
						<el-tag :type="getStatusType(scope.row.status)">
							{{ getStatusText(scope.row.status) }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" min-width="100" align="center">
					<template #default="scope">
						<el-button-group>
							<el-button
								size="small"
								type="primary"
								:icon="View"
								@click="handleViewDetail(scope.row)"
							>
								查看
							</el-button>
							<el-button
								size="small"
								type="success"
								:icon="Edit"
								@click="handleEditStatus(scope.row)"
							>
								状态
							</el-button>
							<el-button size="small" type="danger" :icon="Delete" @click="handleDelete(scope.row)">
								删除
							</el-button>
						</el-button-group>
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页
			<div class="pagination-container">
				<el-pagination
					v-model:current-page="currentPage"
					v-model:page-size="pageSize"
					:page-sizes="[10, 20, 50, 100]"
					layout="total, sizes, prev, pager, next, jumper"
					:total="total"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
				/>
			</div> -->
		</el-card>

		<!-- 详情对话框 -->
		<el-dialog v-model="detailDialogVisible" title="反馈详情" width="50%" destroy-on-close>
			<div v-if="currentFeedback" class="feedback-detail">
				<div class="detail-item">
					<span class="label">标题：</span>
					<span>{{ currentFeedback.title }}</span>
				</div>
				<div class="detail-item">
					<span class="label">类型：</span>
					<span>{{ currentFeedback.type }}</span>
				</div>
				<div class="detail-item">
					<span class="label">内容：</span>
					<p class="content">{{ currentFeedback.content }}</p>
				</div>
				<div class="detail-item">
					<span class="label">用户ID：</span>
					<span>{{ currentFeedback.userId }}</span>
				</div>
				<div class="detail-item" v-if="currentFeedback.contact">
					<span class="label">联系方式：</span>
					<span>{{ currentFeedback.contact }}</span>
				</div>
				<div class="detail-item">
					<span class="label">创建时间：</span>
					<span>{{ formatDate(currentFeedback.createTime) }}</span>
				</div>
				<div class="detail-item">
					<span class="label">状态：</span>
					<el-tag :type="getStatusType(currentFeedback.status)">
						{{ getStatusText(currentFeedback.status) }}
					</el-tag>
				</div>
			</div>
			<template #footer>
				<el-button @click="detailDialogVisible = false">关闭</el-button>
				<el-button type="primary" @click="handleEditStatus(currentFeedback)">更改状态</el-button>
			</template>
		</el-dialog>

		<!-- 状态编辑对话框 -->
		<el-dialog v-model="statusDialogVisible" title="更新反馈状态" width="30%" destroy-on-close>
			<el-form v-if="currentFeedback" :model="statusForm" label-width="80px">
				<el-form-item label="当前状态">
					<el-tag :type="getStatusType(currentFeedback.status)">
						{{ getStatusText(currentFeedback.status) }}
					</el-tag>
				</el-form-item>
				<el-form-item label="新状态">
					<el-radio-group v-model="statusForm.status">
						<el-radio label="resolved">已解决</el-radio>
						<el-radio label="resolving">解决中</el-radio>
						<el-radio label="noResolved">不解决</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="statusDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="updateFeedbackStatus" :loading="submitting">
					确认更新
				</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Delete, Search, RefreshRight, View, Edit } from '@element-plus/icons-vue'
import {
	getFeedBackService,
	deleteFeedBackService,
	updateFeedBackService, // 假设有此API，如果没有需要创建
	getFeedBackListBySpecificService
} from '@/api/feedBack'

// 状态和过滤数据
const feedbackList = ref<any[]>([])
const loading = ref(false)
const submitting = ref(false)
const selectedFeedbacks = ref<any[]>([])
const currentFeedback = ref<any>(null)
const detailDialogVisible = ref(false)
const statusDialogVisible = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 筛选表单数据
const filterForm = reactive({
	type: '',
	status: '',
	keyword: ''
})

// 状态修改表单
const statusForm = reactive({
	status: ''
})

// 获取反馈列表
const fetchFeedbackList = async () => {
	loading.value = true
	try {
		const response = await getFeedBackService()
		if (response.data && response.data.code === 1) {
			feedbackList.value = response.data.data || []
			total.value = response.data.total || feedbackList.value.length
		} else {
			ElMessage.error(response.data?.msg || '获取反馈列表失败')
		}
	} catch (error) {
		console.error('获取反馈列表失败:', error)
		ElMessage.error('获取反馈列表失败')
	} finally {
		loading.value = false
	}
}

// 处理筛选
const handleFilter = async () => {
	loading.value = true

	const params = {
		type: filterForm.type,
		status: filterForm.status
	}

	// 移除null属性
	const filteredParams = Object.fromEntries(
		Object.entries(params).filter(([_, value]) => value !== null && value !== '')
	)

	const res = await getFeedBackListBySpecificService(filteredParams)
	if (res.data && res.data.code === 1) {
		feedbackList.value = res.data.data || []
		// total.value = res.data.total || feedbackList.value.length
		loading.value = false
	} else {
		ElMessage.error(res.data?.msg || '获取反馈列表失败')
		loading.value = false
	}
}

// 重置筛选
const resetFilter = () => {
	filterForm.type = ''
	filterForm.status = ''
	filterForm.keyword = ''
	currentPage.value = 1
	fetchFeedbackList()
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
	pageSize.value = val
	fetchFeedbackList()
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
	currentPage.value = val
	fetchFeedbackList()
}

// 处理表格选择变化
const handleSelectionChange = (selection: any[]) => {
	selectedFeedbacks.value = selection
}

// 查看详情
const handleViewDetail = (row: any) => {
	currentFeedback.value = row
	detailDialogVisible.value = true
}

// 编辑状态
const handleEditStatus = (row: any) => {
	currentFeedback.value = row
	statusForm.status = row.status
	statusDialogVisible.value = true
}

// 更新反馈状态
const updateFeedbackStatus = async () => {
	if (!currentFeedback.value || !statusForm.status) return

	submitting.value = true
	try {
		const response = await updateFeedBackService({
			id: currentFeedback.value.id,
			status: statusForm.status
		})

		if (response.data && response.data.code === 1) {
			ElMessage.success('状态更新成功')
			statusDialogVisible.value = false

			// 更新本地数据
			const index = feedbackList.value.findIndex((item) => item.id === currentFeedback.value.id)
			if (index !== -1) {
				feedbackList.value[index].status = statusForm.status
			}

			// 如果详情框还是打开的，也更新那里的状态
			if (detailDialogVisible.value && currentFeedback.value) {
				currentFeedback.value.status = statusForm.status
			}
		} else {
			ElMessage.error(response.data?.msg || '状态更新失败')
		}
	} catch (error) {
		console.error('状态更新失败:', error)
		ElMessage.error('状态更新失败')
	} finally {
		submitting.value = false
	}
}

// 处理单个删除
const handleDelete = async (row: any) => {
	try {
		await ElMessageBox.confirm('确定要删除这条反馈吗？', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		})

		const res = await deleteFeedBackService([row.id])
		if (res.data && res.data.code === 1) {
			ElMessage.success('删除成功')
			fetchFeedbackList()
		} else {
			ElMessage.error(res.data?.msg || '删除失败')
		}
	} catch (error) {
		console.error('删除失败:', error)
		if (error !== 'cancel') {
			ElMessage.error('删除失败')
		}
	}
}

// 处理批量删除
const handleBatchDelete = async () => {
	if (selectedFeedbacks.value.length === 0) return

	try {
		await ElMessageBox.confirm(
			`确定要删除选中的 ${selectedFeedbacks.value.length} 条反馈吗？`,
			'提示',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}
		)

		const ids = selectedFeedbacks.value.map((item) => item.id)
		const res = await deleteFeedBackService(ids)
		if (res.data && res.data.code === 1) {
			ElMessage.success('批量删除成功')
			fetchFeedbackList()
		} else {
			ElMessage.error(res.data?.msg || '批量删除失败')
		}
	} catch (error) {
		console.error('批量删除失败:', error)
		if (error !== 'cancel') {
			ElMessage.error('批量删除失败')
		}
	}
}

// 格式化日期
const formatDate = (dateString: string) => {
	if (!dateString) return ''
	const date = new Date(dateString)
	const year = date.getFullYear()
	const month = String(date.getMonth() + 1).padStart(2, '0')
	const day = String(date.getDate()).padStart(2, '0')
	const hours = String(date.getHours()).padStart(2, '0')
	const minutes = String(date.getMinutes()).padStart(2, '0')

	return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 获取状态类型
const getStatusType = (status: string) => {
	const statusMap: Record<string, string> = {
		resolved: 'success',
		resolving: 'warning',
		noResolved: 'danger'
	}
	return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
	const statusMap: Record<string, string> = {
		resolved: '已解决',
		resolving: '解决中',
		noResolved: '不解决'
	}
	return statusMap[status] || '未知'
}

// 页面加载时获取反馈列表
onMounted(() => {
	fetchFeedbackList()
})
</script>

<style lang="scss" scoped>
.feedback-manage-container {
	padding: 20px;

	.page-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;

		h2 {
			font-size: 24px;
			margin: 0;
		}

		.header-actions {
			display: flex;
			gap: 10px;
		}
	}

	.filter-card {
		margin-bottom: 20px;

		.el-select {
			width: 100px;
		}
	}

	.data-card {
		.loading-container {
			padding: 30px;
		}

		.empty-data {
			padding: 50px 0;
		}

		.el-table {
			margin-bottom: 20px;
		}
	}

	.pagination-container {
		display: flex;
		justify-content: flex-end;
		margin-top: 20px;
	}

	.feedback-detail {
		.detail-item {
			margin-bottom: 15px;

			.label {
				font-weight: bold;
				color: #606266;
				margin-right: 10px;
			}

			.content {
				background-color: #f8f8f8;
				padding: 15px;
				border-radius: 4px;
				white-space: pre-wrap;
				margin-top: 8px;
			}
		}
	}
}

.el-button-group {
	display: flex;
	justify-content: space-between;
	flex: 1;
}
</style>
